package cn.stimd.spring.format.number;

import cn.stimd.spring.format.Formatter;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class NumberStyleFormatter implements Formatter<Number> {
    private String pattern;

    public NumberStyleFormatter() { }

    public NumberStyleFormatter(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public Number parse(String text, Locale locale) throws ParseException {
        return getNumberFormat(locale).parse(text);
    }

    @Override
    public String print(Number number, Locale locale) {
        return getNumberFormat(locale).format(number);
    }

    private NumberFormat getNumberFormat(Locale locale) {
        //处理普通的数值
        NumberFormat format = NumberFormat.getInstance(locale);
        if (!(format instanceof DecimalFormat)) {
            if (this.pattern != null) {
                throw new IllegalStateException("Cannot support pattern for non-DecimalFormat: " + format);
            }
            return format;
        }

        //处理Decimal数值
        DecimalFormat decimalFormat = (DecimalFormat) format;
        decimalFormat.setParseBigDecimal(true);
        if (this.pattern != null) {
            decimalFormat.applyPattern(this.pattern);
        }
        return decimalFormat;
    }
}
